<?php
declare(strict_types=1);

namespace app\admin\controller;

use app\common\controller\BaseController;
use app\common\model\Dict as DictModel;
use app\common\model\DictLang as DictLangModel;
use app\common\model\DictItem as DictItemModel;
use app\common\utils\JsonResponse;
use think\facade\Db;
use think\facade\Request;

class Dict extends BaseController
{
    /**
     * 处理多语言数据
     * @param array $langs 语言数据数组
     * @return array 处理后的语言数据
     */
    protected function processLangData(array $langs): array
    {
        $result = [];
        
        // 遍历语言数据
        foreach ($langs as $lang) {
            // 如果没有提供name，则跳过该语言
            if (empty($lang['name'])) {
                continue;
            }
            
            // 确保language_id存在且有效
            if (empty($lang['language_id'])) {
                continue;
            }
            
            // 添加到结果数组
            $result[] = [
                'language_id' => (int)$lang['language_id'],
                'name' => trim($lang['name']),
                'remark' => !empty($lang['remark']) ? trim($lang['remark']) : ''
            ];
        }
        
        // 检查是否至少有一种语言
        if (empty($result)) {
            throw new \Exception('至少需要一种语言的数据');
        }
        
        return $result;
    }

    /**
     * 获取字典列表
     * @permission system:dict:getList
     */
    public function getList()
    {
        $params = Request::get();
        
        $list = DictModel::with(['langs.language'])
            ->withSearch(['name', 'code', 'type', 'status'], $params)
            ->withAttr('item_count', function($value, $data) {
                return DictItemModel::where('dict_id', $data['dict_id'])->count();
            })
            ->order('sort', 'asc')
            ->select();

        return JsonResponse::success([
            'list' => $list
        ]);
    }
    
    /**
     * 添加字典
     * @permission system:dict:doAdd
     */
    public function doAdd()
    {
        $params = Request::post();
        
        Db::startTrans();
        try {
            // 检查编码是否已存在
            if (DictModel::where('code', $params['code'])->find()) {
                throw new \Exception('字典编码已存在');
            }
            
            // 处理语言数据
            $langs = $this->processLangData($params['langs'] ?? []);
            
            // 创建字典主表数据
            $dict = DictModel::create([
                'code' => $params['code'],
                'type' => $params['type'],
                'sort' => $params['sort'] ?? 0,
                'status' => $params['status'] ?? 1
            ]);
            
            // 创建字典语言数据
            foreach ($langs as $lang) {
                DictLangModel::create([
                    'dict_id' => $dict->dict_id,
                    'language_id' => $lang['language_id'],
                    'name' => $lang['name'],
                    'remark' => $lang['remark']
                ]);
            }
            
            Db::commit();
            return JsonResponse::success([], '添加成功');
        } catch (\Exception $e) {
            Db::rollback();
            return JsonResponse::error($e->getMessage());
        }
    }
    
    /**
     * 编辑字典
     * @permission system:dict:doEdit
     */
    public function doEdit()
    {
        $params = Request::post();
        
        Db::startTrans();
        try {
            // 检查记录是否存在
            $dict = DictModel::find($params['dict_id']);
            if (!$dict) {
                throw new \Exception('字典不存在');
            }
            
            // 检查编码是否重复(排除自身)
            if (DictModel::where('code', $params['code'])
                ->where('dict_id', '<>', $params['dict_id'])
                ->find()) {
                throw new \Exception('字典编码已存在');
            }
            
            // 处理语言数据
            $langs = $this->processLangData($params['langs'] ?? []);
            
            // 更新主表数据
            $dict->save([
                'code' => $params['code'],
                'type' => $params['type'],
                'sort' => $params['sort'] ?? 0,
                'status' => $params['status'] ?? 1
            ]);
            
            // 获取现有的语言数据
            $existingLangs = DictLangModel::where('dict_id', $params['dict_id'])
                ->column('*', 'language_id');
            
            // 更新语言数据
            foreach ($langs as $lang) {
                $langId = $lang['language_id'];
                
                if (isset($existingLangs[$langId])) {
                    // 更新已存在的语言数据
                    DictLangModel::update([
                        'name' => $lang['name'],
                        'remark' => $lang['remark'],
                        'dict_lang_id' => $existingLangs[$langId]['dict_lang_id']
                    ]);
                    // 从现有数据中移除已处理的语言
                    unset($existingLangs[$langId]);
                } else {
                    // 创建新的语言数据
                    DictLangModel::create([
                        'dict_id' => $dict->dict_id,
                        'language_id' => $langId,
                        'name' => $lang['name'],
                        'remark' => $lang['remark']
                    ]);
                }
            }
            
            Db::commit();
            return JsonResponse::success([], '更新成功');
        } catch (\Exception $e) {
            Db::rollback();
            return JsonResponse::error($e->getMessage());
        }
    }
    
    /**
     * 删除字典
     * @permission system:dict:doDelete
     */
    public function doDelete()
    {
        $dictId = Request::param('dict_id');
        
        Db::startTrans();
        try {
            // 检查记录是否存在
            $dict = DictModel::find($dictId);
            if (!$dict) {
                throw new \Exception('字典不存在');
            }
            
            // 删除主表数据
            $dict->delete();
            
            // 删除关联的语言数据
            DictLangModel::where('dict_id', $dictId)->delete();
            
            Db::commit();
            return JsonResponse::success([], '删除成功');
        } catch (\Exception $e) {
            Db::rollback();
            return JsonResponse::error($e->getMessage());
        }
    }
} 